import React, { useEffect, useState } from 'react'
import './article.scss'
import ArticleItem from '../../components/Article/ArticleItem'
import Title from '../../components/Title/Title'
import Pagination from '../../components/Pagination/Pagination'
import axios from '../../axios'

export default function Article(props) {

  const [categoryList, setCategoryList] = useState([])
  const [categoryId, setCategoryId] = useState(null)

  const [articleList, setArticleList] = useState([])
  const [pageSize] = useState(10)
  const [pageIndex, setPageIndex] = useState(1)
  const [total, setTotal] = useState(0)

  useEffect(() => {
    axios.get('/article', {
      pageIndex,
      pageSize,
      category: categoryId
    }).then(res => {
      console.log(res)
      setArticleList(res.data.records)
      setTotal(res.data.total)
      if (pageIndex > 1) {
        window.scrollTo({
          left: 0,
          top: 200,
          behavior: 'smooth'
        })
      }
    })
  }, [pageIndex, pageSize, categoryId])

  useEffect(() => {
    axios.get('/category').then(res => {
      setCategoryList(res.data)
      console.log(res.data)
    })
  }, [])

  const categoryChange = (id) => {
    setCategoryId(id)
  }

  const changePageIndex = (index) => {
    setPageIndex(index)
  }

  return (
    <div className='article'>
      <div className='categories'>
        <span className={ !categoryId ? 'category-item active' : 'category-item' } onClick={() => categoryChange(null)}>全部</span>
        {
          categoryList.map((item) => {
            return (
              <span className={ item._id===categoryId ? 'category-item active' : 'category-item' } key={item._id} onClick={() => categoryChange(item._id)}>{item.name}</span>
            )
          })
        }
      </div>
      <Title>{categoryList.find(item => item._id === categoryId)?.name || '全部'}</Title>
      <div className='list'>
        {
          articleList.map(item => {
            return (
              <ArticleItem key={item._id} {...item}></ArticleItem>
            )
          })
        }
      </div>
      <Pagination current={pageIndex} pageSize={pageSize} total={total} change={changePageIndex}></Pagination>
    </div>
  )
}
